<style scoped>
  .weui-form-preview__hd label,
  .weui-form-preview__hd em {
    font-size: .9em !important;
  }

  .rj-cell.max span {
    font-size: 16px;
    padding-right: 20px;
  }

  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }

  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }

  .rj-cell.note label {
    float: left;
  }

  .rj-cell.note span {
    width: 80%;
    display: inline-block;
  }

  .weui-cells {
    margin-top: 0;
  }

  .weui-cells_form {
    background: #fbfbfb;
  }

  .weui-cell {
    background: #fff;
  }

  #acts span {
    font-size: 14px;
  }

  .weui-label {
    text-align: left;
  }

  .time {
    border: none;
    font-size: 17px;
    background: #fff;
  }

  .weui-cell_select {
    padding: 10px 15px;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }

  .weui_uploader_files {
    list-style: none;
  }

  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }

  .weui_uploader_input_wrp:before,
  .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }

  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }

  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }

  .weui_uploader_bd {
    overflow: hidden;
  }

  .outstore>>>.weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }

  .weui-cell.fir {
    border-top: 0;
  }

  .weui_uploader_input_wrp.inrow {
    width: 30px;
    height: 30px;
    margin: 0;
  }

  .weui_uploader_input_wrp:before {
    height: 19.5px;
  }

  .weui_uploader_input_wrp:after {
    width: 19.5px;
  }

  .weui-uploader_file.inrow {
    margin: 0;
    width: 40px;
  }

  li.weui-uploader_file {
    display: inline-block;
    padding: 3px 5px;
  }

  ul#images {
    text-align: right;
  }
</style>
<template>
  <div class="comon">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      {{title}}
      <a href="javascript:;" @click="$router.push({name: 'Sellform'})" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form method="post" id="formid">
        <input type="hidden" name="entity.deliProvince" :value="currStroom.province" />
        <input type="hidden" name="entity.deliCity" :value="currStroom.city" />
        <input type="hidden" name="entity.deliDistrict" :value="currStroom.area" />
        <input type="hidden" name="entity.arriProvince" v-model="packCitys.split(' ')[0] || wlLand.arriProvince" />
        <input type="hidden" name="entity.arriCity" v-model="packCitys.split(' ')[1] || wlLand.arriCity" />
        <input type="hidden" name="entity.arriDistrict" v-model="packCitys.split(' ')[2] || wlLand.arriDistrict" />
        <input type="hidden" name="entity.type" value="2" />
        <input type="hidden" name="entity.sort" :value="wlLand.sort || wlSea.sort" />
<!--        <input type="hidden" name="entity.mainidsea" :value="wlLand.guid" readonly />-->
        <input type="hidden" name="entity.guid" :value="id"/>
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label" ref="msgDiv" style="width: 66px;">申请人</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input notnull" type="text" name="entity.applyname" readonly="true" :value="data.applyname">
              <input class="weui-input notnull" name="entity.depname" ref="depname" readonly :value="data.depname" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">货品类型</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.quitSRType" :value="data.quitSRType">
              <input class="weui-input" readonly type="text" :value="data.quitSRTypeName" placeholder="暂无数据">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">订单类型</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.flag" :value="data.flag">
              <input class="weui-input" readonly type="text" :value="data.flagname" placeholder="暂无数据">
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell fir">
            <div class="weui-cell__hd"><label class="weui-label">客户</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.customerguid" :value="data.customerguid"/>
<!--              <input type="hidden" name="entity.customerid" :value="data.customerguid"/>-->
<!--              <input type="hidden" name="entity.customername" :value="data.customername"/>-->
              <input type="text" readonly style="border: 0;font-size: 16px;" name="entity.customername" :value="data.customername"/>
            </div>
          </div>
          <div class="weui-cell" v-if="contracts.length > 0">
            <div class="weui-cell__hd"><label class="weui-label">销售合同</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" class="weui-input" :value="contracts[0].guid" name="entity.contractid">
              <input type="hidden" class="weui-input" :value="contracts[0].code" name="entity.contractcode">
              <input class="weui-input" type="text" :value="contracts[0].name" name="entity.contractname" readonly>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">收货城市</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="endCity" name="" v-model="packCitys"  >
            </div>
<!--            <div class="weui-cell__ft" v-if="hasCustomer">-->
<!--              <div class="weui-vcode-btn" @click="manageAddr"><i class="weui-icon-info-circle"></i></div>-->
<!--            </div>-->
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">详细地址</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="arriAddress" name="entity.arriAddress" :value="wlLand.arriAddress" readonly placeholder="请输入收货详细地址">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">收货联系人</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="arriContact" name="entity.arriContact" :value="wlLand.arriContact" readonly placeholder="请输入收货联系人">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">联系电话</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="arriContactNo" name="entity.arriContactNo" :value="wlLand.arriContactNo" readonly placeholder="请输入收货人电话">
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">物流结算</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.faretype" :value="wlLand.faretype"/>
              <input type="text" style="border: 0;font-size: 16px;" readonly name="entity.faretypeName" :value="wlLand.faretypeName"/>
            </div>
          </div>

          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">配送方式</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.deliverytype" :value="data.deliverytype"/>
              <input type="text" style="border: 0;font-size: 16px;" readonly name="entity.deliverytypename" :value="data.deliverytypename"/>
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell weui-cell_select fir">
            <div class="weui-cell__hd"><label class="weui-label">计价方式</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.settletype" :value="data.settletype"/>
              <input type="text" style="border: 0;font-size: 16px;" name="entity.settletypename" readonly :value="getCurrencyName(data.settletype, settletypes)" />
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">结算币种</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.currency" :value="data.currency"/>
              <input type="text" style="border: 0;font-size: 16px;" name="entity.currencyname" readonly :value="getCurrencyName(data.currency, currencys)"/>
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">付款方式</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.paytype" :value="data.paytype"/>
              <input type="text" style="border: 0;font-size: 16px;" readonly name="entity.paytypename" :value="data.paytypename" />
            </div>
          </div>
          <div class="weui-cell weui-cell_select" v-if="paytype == 3">
            <div class="weui-cell__hd"><label class="weui-label">结算账期</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.settlebilling" :value="data.settlebilling"/>
              <input type="text" style="border: 0;font-size: 16px;" readonly :value="getCurrencyName(data.settlebilling, settlebillings)"/>
            </div>
          </div>
          <div class="weui-cell" v-if="settlebilling == 2">
            <div class="weui-cell__hd"><label class="weui-label">收到发票后结算天数</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly type="number" name="entity.settledays" placeholder="请输入收到发票后结算天数">
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell fir">
            <div class="weui-cell__hd"><label class="weui-label">库存组织</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select rj-line-select" name="" v-model="org">
                <option value="" disabled>请选择</option>
                <option v-for="(item, index) in orgs" :value="item.guid">
                  {{item.name}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">出库库房</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.storermguid" id="storermname" v-model="storermid">
                <option value="" disabled>请选择</option>
                <option v-for="(item, index) in storerooms" :value="item.guid">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">发货城市</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="startCity" name="" :value="currStroom != '' ? currStroom.province + ' ' + currStroom.city + ' ' + currStroom.area : ''" placeholder="请选择发货城市" >
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">详细地址</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input notnull" type="text" id="deliAddress" name="entity.deliAddress" :value="currStroom.address" placeholder="请输入发货详细地址">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">发货联系人</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="deliContact" name="entity.deliContact" :value="currStroom.contact" placeholder="请输入发货联系人">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">联系电话</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="deliContactNo" name="entity.deliContactNo" :value="currStroom.contacttel" placeholder="请输入发货人电话">
            </div>
          </div>
          <div class="weui-cell fir">
            <div class="weui-cell__hd">
              <label class="weui-label">发货日期</label>
            </div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.senddate" :value="data.senddate" />
              <input type="text" id='datetime-picker' v-model="data.senddate" class="time" name="" placeholder="请选择要求发货日期" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd">
              <label class="weui-label">到货日期</label>
            </div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.arrivedate" :value="data.arrivedate" />
              <input type="text" id='datetime-picker2' v-model="data.arrivedate" class="time" name="" placeholder="请选择要求到货日期" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">附件上传</label></div>
            <div class="weui-cell__ft">
              <div class="weui_uploader_bd">
                <ul class="weui_uploader_files"></ul>
                <div class="weui_uploader_input_wrp inrow">
                  <UploadFile class="weui_uploader_input" :orderid="id" v-on:pushfile="setFile"></UploadFile>
                </div>
              </div>
            </div>
            <ul class="weui-uploader_files" id="images">
              <li class="weui-uploader_file" v-for="(fil, index) in filenames" :key="index" @click="delFile(fil,fileids[index])">
                {{fil}}
              </li>
            </ul>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="entity.remarks" v-model="data.remarks" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>
        <DivideOrderItem v-for="(item, index) in listdata.oitems" :key="item.guid" :initItemlen="itemlen" :itemNo="index" :itemdata="item" :isLast="index+1 == listdata.oitems.length" :quitsrtype="quitsrtype" :settletype="settletype" :paytype="paytype" :benifitordeduct="benifitordeduct" :benefittype="benefittype" :discount="discount" :prodpricestra="prodpricestra" :currency="currency" :orgid="currDepart.orgguid" :orderAmount="orderAmount" :childAmount="childAmount" @computeAmount="computeTotalAmt" @doDelItem="delItem"></DivideOrderItem>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary subbtn" href="javascript:" @click="postForm(2)">提交</a>
        </div>

      </form>

    </div>
  </div>
</template>

<script>
  import DivideOrderItem from "./DivideOrderItem";
  import UploadFile from "../common/UploadFile";

  export default {
    name: 'DivideOrder',
    data() {
      return {
        openid: localStorage.openid, //'oIuV2v77MaLCAQILhjI6h6oTWpHI',
        username: localStorage.username,
        customers: [],
        currCustomer: '',
        customerid: '',
        departments: [],
        currDepart: '',
        departid: '',
        defaultDep: {},
        fpricetypes: [], //运费计价方式（按车、按吨）
        fpricetype: 1,
        salestypes: [],
        defSaletype: {},
        faretypes: [], //物流结算方式（公司结算、客户结算）
        faretypekey: 1,
        defFaretype: {},
        customerguid: '',
        customername: '',
        rcamount: '',
        storeCitys: {},
        storeAddrs: {},
        storeRnames: {},
        storeTels: {},
        customerCitys: {},
        customerAddrs: {},
        customerRnames: {},
        customerTels: {},
        itemRemarks: {},
        cusrcamounts: {},
        products: [],
        saleSpec: [],
        oitems: [0],
        contracts: [],
        quitsrtype: 2,
        storerooms: [],
        currStroom: '',
        storermid: '',
        settletypes: [],
        settletype: 1,
        paytypes: [], //付款方式（全额预付、上车付款、到货付款）
        paytype: 1,
        flag: 1,
        deliverytypes: [],
        deliverytype: 2,
        benifitordeduct: '',
        benefittype: '',
        discount: '',
        currencys: [], //结算币种
        currency: 1,
        settlebillings: [], //结算账期
        settlebilling: 1,
        prodpricestra: 2, //为1获取不到价格不许提交，2.允许手动录入,
        senddate: '',
        arrivedate: '',
        filenames: [],
        fileids: [],
        contractParam: '',
        ordertypes: [],
        data: {},
        id: '',
        title: '',
        nodeid: '',
        annex: '',
        spitems: [],
        wlLand: '',
        wlSea: '',
        itemlen: 0,
        listdata: {},
        totalAmount: 0,
        childAmount: 0,
        orderAmount: 0,
        partitiontype: '',
        itemsCount: '',
        wlMail: '',
        packCitys: '',
        orgs: [],
        org: '',
      }
    },
    components: {
      DivideOrderItem,
      UploadFile
    },
    computed: {
      hasCustomer: function () {
        return this.customerid != '' ? true : false;
      },
    },
    created() {

      window.addEventListener('setItem', () => {
        this.openid = localStorage.getItem('openid');
        this.username = localStorage.getItem('username');
      })
    },
    async mounted() {
      let that = this;
      this.id = this.$route.query.guid;
      this.nodeid = this.$route.query.nodeid;
      this.annex = this.$route.query.annex;
      this.title = this.$route.query.title;
      this.partitiontype = this.$route.query.partitiontype;

      //日历初始化
      $("#datetime-picker").calendar({
        dateFormat: 'yyyy-mm-dd'
      });
      $("#datetime-picker2").calendar({
        dateFormat: 'yyyy-mm-dd'
      });

      //获取select下拉数据
      //this.getCustomer();
      this.getDiscountType();
      this.getOrgs();
      this.getFpricetype(); //运费计价方式
      this.getSalestype();
      this.getOrdertype();
      this.getFaretype();
      this.getSettletypes();
      this.getDeliverytypes();
      this.getCurrencys();
      this.getSettlebillings();
      this.getPaytypes();
      this.checkPartition();
      //获取再次下单的数据
      await this.getOrderNext()
      //地址初始化
      $("#startCity").cityPicker();
      $("#startCity").change(function () {
        let addr = $(this).val().split(' ');
        $('input[name="entity.deliProvince"]').val(addr[0]);
        $('input[name="entity.deliCity"]').val(addr[1]);
        $('input[name="entity.deliDistrict"]').val(addr[2]);
      })
      $("#endCity").cityPicker();
      $("#endCity").change(function () {
        that.packCitys = $(this).val();
      })
    },
    activated() {
      //从state中获取数据并赋值
      if (this.$store.state.arriAddr.address != '') {
        this.getStateAddr();
      } else {
        this.setCustomer();
      }
    },
    watch: {
      'departid': function (data) {
        this.currDepart = this.departments.filter(function (item) {
          return item.guid == data;
        })[0] || '';
        this.getCustomer(data);
      },
      'customerid': function (data) {
        this.currCustomer = this.customers.filter(function (item) {
          return item.guid == data;
        })[0] || '';
        this.currency = this.currCustomer.currency != '' ? this.currCustomer.currency : 1;
        this.$store.commit('setCustomer', this.currCustomer);

        this.getContract();
        //电商订单
        if (this.currCustomer.flag == 1) {
          this.flag = 4;
        } else {
          this.flag = 1;
        }
      },
      'org': function (val) {
        this.getStorms(val);
        this.storermid = '';
      },
      'storermid': function (data) {
        this.currStroom = this.storerooms.filter(function (item) {
          return item.guid == data;
        })[0] || '';
      }
    },
    methods: {
      checkPartition: function() {
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!checkPartition.action',
          params: {
            orderid: this.id
          }
        }).then(response => {
          if (response.data.msg == 'success') {
            this.childAmount = response.data.amounts.childAmount;
            this.orderAmount = response.data.amounts.orderAmount;
            console.log('response.data.amounts.orderAmount:', this.orderAmount)
          }
        })
      },
      computeTotalAmt: function(amount) {
        this.totalAmount += amount;
        console.log('totalAmount:', this.totalAmount)
      },
      getCurrencyName: function(val, listdata) {
        if (val == undefined) return;
        if (listdata.length > 0) {
          return listdata.filter(item => {
            return item.dictkey == val;
          })[0].dicttext;
        }
      },
      async getOrderNext() {
        let that = this;
        await this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!review.action',
          params: {
            sellformid: this.id,
            partitiontype: this.partitiontype,
          }
        }).then(response => {
          this.data = response.data.form;
          this.spitems = response.data.spitems;
          this.itemsCount = response.data.itemsCount;
          response.data.wl.forEach(function (item) {
            if (item.transtype == 1 || item.transtype == 3) {
              that.wlLand = item;
            } else if (item.transtype == 2) {
              that.wlSea = item;
            }
          });
          that.packCitys = that.wlLand.arriProvince != undefined ? that.wlLand.arriProvince + ' ' + that.wlLand.arriCity + ' ' + that.wlLand.arriDistrict : '';
          this.itemlen = this.data.items.length + this.spitems.length;
          console.log('this.itemlen:', this.itemlen)
          this.$set(this.listdata, 'oitems', this.spitems.concat(this.data.items));
          this.listdata.oitems.map(item =>{
            item.finishCount = item.spguid != undefined ? this.itemsCount[item.spguid] : this.itemsCount[item.speguid];
            item.finishCount = item.finishCount != null ? item.finishCount : 0;
          })

           this.currCustomer = this.data.customer;
          this.quitsrtype = this.data.quitsrtype;

          if (this.departments.length > 0) {
            this.departid = this.baseInfo.depguid;
          }
          this.flag = this.data.flag;
          this.faretypekey = this.wlLand.faretype;
          this.deliverytype = this.data.deliverytype;
          this.settletype = this.data.settletype;
          this.currency = this.data.currency;
          this.paytype = this.data.paytype;
          this.settlebilling = this.data.settlebilling;
          this.transType = this.data.transType;
        })
      },
      delFile: function (name, id) {
        let that = this;
        $.confirm('确定要删除？', function () {
          that.axios({
            method: 'post',
            url: '/sales/Fileinfo!delete.action',
            params: {
              fileid: id
            }
          })
          that.fileids = that.fileids.filter(item => {
            return item != id;
          })
          that.filenames = that.filenames.filter(item => {
            return item != name;
          })
        })
      },
      setFile: function (file) {
        this.filenames.push(file.name);
        this.fileids.push(file.id);
      },
      addItem: function (index) {
        this.oitems.push(index);
      },
      delItem: function (id) {
        this.listdata.oitems = this.listdata.oitems.filter(item => {
          return item.guid != id;
        });
        this.itemlen = this.listdata.oitems.length;
      },
      toBigorder: function () {
        let that = this;
        $.confirm("按大订单流程处理?", function () {
          that.flag = 2;
        });
      },
      setCustomer: function () {
        this.currCustomer = this.$store.state.customer;
      },
      manageAddr: function () {
        this.$router.push({
          name: 'AddressList'
        });
        return false;
      },
      getStateAddr: function () {
        let addr = this.$store.state.arriAddr;

        $('input[name="entity.arriProvince"]').val(addr.province);
        $('input[name="entity.arriCity"]').val(addr.city);
        $('input[name="entity.arriDistrict"]').val(addr.district);
        // $('#endCity').val(addr.province + ' ' + addr.city + ' ' + addr.district);
        $('#arriAddress').val(addr.address);
        $('#arriContact').val(addr.contact);
        $('#arriContactNo').val(addr.contactno);
      },
      //客户
      filterCustomer: function (item) {

        let sname = item.name;
        this.customerCitys[sname] = item.province + ' ' + item.city + ' ' + item.district;
        this.customerAddrs[sname] = item.address;
        this.customerRnames[sname] = item.contact;
        this.customerTels[sname] = item.contactno;
        this.cusrcamounts[sname] = item.rcamount != '' ? item.rcamount : 0;
        return {
          title: item.name,
          value: item.guid
        };
      },
      getCustomer: function (departid) {
        let that = this
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Customer!getCustomers.action',
          params: {
            departid: departid,
            functiontype: 13
          }
        }).then(response => {
          if (response.data.msg == "success") {
            that.customers = response.data.customers;
          } else {
            this.toastText('获取客户数据失败');
          }
        });
      },
      getContract: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Salecontract!getContract.action',
          params: {
            customerid: this.customerid,
            orgguid: this.currDepart.orgguid,
            status: 1
          }
        }).then(response => {
          let data = response.data;
          if (data.code == 1) {
            this.contracts = data.msg;
          } else if (data.code == 0) {
            this.toastText(data.msg);
          } else {
            this.toastText('获取销售合同数据失败');
          }
        });
      },
      getDiscountType: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!getDiscountType.action',
          params: {
            type: this.quitsrtype
          }
        }).then(response => {
          let data = response.data;
          if (data.code == 1) {
            this.benifitordeduct = data.msg.benifitordeduct;
            this.benefittype = data.msg.benefittype;
            this.discount = data.msg.discount;
            this.prodpricestra = data.msg.prodpricestra;
            this.contractParam = data.msg.contractParam;
          } else if (data.code == 0) {
            this.toastText(data.msg);
          } else {
            this.toastText('获取赠送数据失败');
          }
        });
      },
      //部门
      filterDepartment: function (item) {
        return {
          title: item.name,
          value: item.guid
        };
      },
      getDepartment: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDepartment.action',
          params: {
            sPermission: 2
          }
        }).then(response => {
          if (response.data.status == "true") {
            that.departments = response.data.result;
          } else if (response.data.status == "false") {
            this.toastText(response.data.result);
          } else {
            this.toastText('获取部门数据失败');
          }
        });
      },
      //运费计价方式
      filterFpricetype: function (item) {
        return {
          title: item.dicttext,
          value: item.dictkey
        };
      },
      getFpricetype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 94
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.fpricetypes = response.data;
          } else {
            this.toastText('获取运费计价方式数据失败');
          }
        });
      },
      //销售形式
      getSalestype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 13
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.salestypes = response.data.map(that.filterFpricetype);
            $('#salestype').select({
              title: "选择销售形式",
              items: that.salestypes,
              onChange: function (data) {
                $('input[name="entity.salestype"]').val($('#salestype').data('values'));
              }
            });
          } else {
            this.toastText('获取销售形式数据失败');
          }
        });
      },
      //物流结算
      getFaretype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 19
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.faretypes = response.data;
          } else {
            this.toastText('获取物流结算方式数据失败');
          }
        });
      },
      //订单类型
      getOrdertype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 47
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.ordertypes = response.data;
          } else {
            this.toastText('获取订单类型数据失败');
          }
        });
      },
      getSettletypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 93
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.settletypes = response.data;
          } else {
            this.toastText('获取结算方式数据失败');
          }
        });
      },
      getDeliverytypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 48
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.deliverytypes = response.data;
          } else {
            this.toastText('获取物流配送方式数据失败');
          }
        });
      },
      getCurrencys: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 92
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.currencys = response.data;
          } else {
            this.toastText('获取结算币种数据失败');
          }
        });
      },
      getSettlebillings: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 46
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.settlebillings = response.data;
          } else {
            this.toastText('获取结算账期数据失败');
          }
        });
      },
      getPaytypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {
            type: 45
          }
        }).then(response => {
          if (response.statusText == "OK") {
            that.paytypes = response.data;
          } else {
            this.toastText('获取付款方式数据失败');
          }
        });
      },
      //库房
      filterStorms: function (item) {
        let sname = item.name;
        this.storeCitys[sname] = item.province + ' ' + item.city + ' ' + item.area;
        this.storeAddrs[sname] = item.address;
        this.storeRnames[sname] = item.contact;
        this.storeTels[sname] = item.contacttel;
        return {
          title: item.name,
          value: item.guid
        };
      },
      getOrgs: function() {
        this.axios({
          method: 'get',
          url: '/produce/Produceplan!getOrgbyWh.action',
          params: {}
        }).then((response) => {
          if (response.data.status == 'true') {
            this.orgs = response.data.result;
          } else if(response.data.status == 'false') {
            this.toastText(response.data.result);
          } else {
            this.toastError("获取库存组织数据失败");
          }

        })
      },
      getStorms: function (orgid = '') {
        let that = this;
        this.axios({
          method: 'get',
          url: '/produce/Storeroom!getStoreroom.action',
          params: {'entity.orgguid': orgid}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.storerooms = response.data.storeromms;
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastText('获取库房数据失败');
          }
        });
        // this.axios({
        //   method: 'get',
        //   responseType: 'json',
        //   url: '/sales/Sellform!findStorms.action'
        // }).then(response => {
        //   if (response.data.status == "true") {
        //     this.storerooms = response.data.result;
        //   } else {
        //     $.toast('获取库房数据失败', 'text')
        //   }
        // });
      },
      //品种
      filterProductinfo: function (item) {
        return {
          title: item.productname,
          value: item.guid
        };
      },
      filterSalesspec: function (item) {
        let sname = item.name;
        this.itemRemarks[sname] = item.description;
        return {
          title: item.name,
          value: item.guid
        };
      },
      getSalesspec: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findSalesspecification.action'
        }).then(response => {
          if (response.data.status == "true") {

            that.saleSpec = response.data.result;
          } else {
            $.toast('获取规格数据失败', 'text')
          }
        });
      },
      //提交表单数据
      postForm: function (type) {
        if (this.storermid == '') {
          this.toastText('出库库房不能为空！')
          return false;
        }else if (this.settletype == 1 && !this.checkEmy('orderpack')) {
          $.alert('请输入订单数量！');
          return false;
        } else if (this.settletype == 2 && !this.checkEmy('weight')) {
          $.alert('请输入货品重量！');
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled", true).css("pointer-events", "none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData.nodeid = this.nodeid;
        postData.fileids = this.fileids.join(',');
        postData.partitiontype = this.partitiontype;

        this.axios({
          method: 'post',
          url: '/sales/Sellform!partition.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events", "auto");
          //关闭提交状态
          $.hideLoading();
          if (response.data.msg == 'success') {
            if (type == 1) {
              this.toastSuccess("保存成功");
            } else {
              this.toastSuccess("提交成功");
              this.$router.push({
                name: 'Sellform'
              });
            }
          } else {
            if (response.data.msg == "outlogin") {
              this.toastText('请重新登录');
            } else if (response.data.msg == "canotopt") {
              this.toastText('不允许的操作');
            } else if (response.data.msg == "false") {
              this.toastText5(response.data.result);
            } else if (response.data.msg == "yz") {
              let result = response.data.result;
              let txt = '预收款余额不足</br>余额：' + result.prebalance + '</br>在途订单：' + result.ztbalance + '</br>可用余额：' + result.kybalance + '</br>当前订单：' + result.balance;
              this.toastText5(txt);
            } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
              //不不设置提示
            } else {
              $.alert("系统错误");
            }
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events", "auto");
          //关闭提交状态
          $.hideLoading();
          $.alert("系统错误");
        });
      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i = 0; i < $('.oitem').not(':hidden').length; i++) {
          parr1.push({
            [$('.product').eq(i).val()]: $('.specif').eq(i).val()
          });
          parr2.push({
            [$('.product').eq(i).val()]: $('.specif').eq(i).val()
          });
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j = i + 1; j < parr2.length;) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0]) {
              parr2.splice(j, 1); //去除重复的对象；
            } else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      }
    }
  }
</script>
